<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Exception;
use think\Validate;
use app\admin\model\User as UserModel;
use app\admin\model\Follow;
use app\admin\model\Shop;
use app\admin\model\TaskImg;
use app\admin\model\ProductViewLog;
use app\admin\model\UserOrder;
use app\admin\model\UserCollect;
use app\admin\model\UserAddress;
use app\admin\model\Love;
use app\admin\model\Community;
use app\admin\model\Visit;
use app\admin\model\AreaWorldwide;
use app\admin\model\Product;
use app\admin\model\ProductMessage;
use app\admin\model\UserRoseLog;
use app\admin\model\ConfigData;
use app\admin\model\ChatMessage;
use app\admin\model\ProductWish;
use app\admin\model\MobileCode;
use app\admin\model\UserReport;
use app\admin\model\GroupChat;
use app\admin\model\GroupChatUser;
use getui\GeTui;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = [];

	public function _initialize(){
		$action = request()->action();
	
		if(!in_array($action,$this->noNeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
                $headers['token'] = $this->request->request('token');
            }else{
                foreach($_SERVER as $key=>$value){
                    if(substr($key, 0, 5)==='HTTP_'){
                        $key = substr($key, 5);
                        $key = str_replace('_', ' ', $key);
                        $key = str_replace(' ', '-', $key);
                        $key = strtolower($key);
                        if(!in_array($key, $ignore)){
                            $headers[$key] = $value;
                        }
                    }
                }
            }
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=UserModel::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			UserModel::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}
    //获取新消息
    public function getmessage(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        if($is_group_chat){
            $where = [
                'status'=>1,
                'sort'=>$sort
            ];
            $list = ChatMessage::where($where)->order('add_time desc')->limit(0,1)->select();
        }else{
            if(!$sort){
                $where = [
                    'status'=>1,
                    'js_user_id'=>$this->user['id'],
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'is_read'=>0,
                    'user_id'=>$js_user_id
                ];
            }else{
                $where = [
                    'status'=>1,
                    'js_user_id'=>$this->user['id'],
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'is_read'=>0,
                    'sort'=>$sort,
                ];
            }
            $list = ChatMessage::where($where)->order('add_time asc')->select();
        }
       
        $ids = [];
        if($list){
            $avatar = UserModel::where(['id'=>$this->user['id']])->value('avatar');
            $last_time = 0;
            foreach ($list as &$v) {
                //查看用户信息
                if($v['is_read'] == 0){
                    //如果有未读消息则更新为已读
                    $ids[] = $v['id'];
                }
                $where = ['id'=>$v['user_id']];
                $v['avatar'] = $avatar;
                $v['user'] = UserModel::field('id,avatar,nickname')->where($where)->find();
                $v['time'] = '';
                if(!$last_time){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }elseif(($v['add_time'] - $last_time) > 7600){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }

                if($v['type'] == 1){ //文字
                    //判断发布文字有多少个字
                    $len = mb_strlen($v['content'], 'UTF-8');
                    $v['len'] = 135;
                    if($len > 16 && $len <= 32){
                        $v['len'] = 170;
                    }elseif($len > 32 && $len <= 48){
                        $v['len'] = 210;
                    }elseif($len > 48 && $len <= 64){
                        $v['len'] = 250;
                    }elseif($len > 64 && $len <= 80){
                        $v['len'] = 290;
                    }elseif($len > 80 && $len <= 96){
                        $v['len'] = 330;
                    }elseif($len > 96 && $len <= 122){
                        $v['len'] = 370;
                    }elseif($len > 122 && $len <= 138){
                        $v['len'] = 410;
                    }elseif($len > 138){
                        $v['len'] = 450;
                    }
                }elseif($v['type'] == 2){ //图片
                    $v['len'] = 290;
                }elseif($v['type'] == 3){ //商品
                    $v['len'] = 270;
                    $v['product'] = Product::field('id,video_img,title,price')->where(['id'=>$v['goods_id']])->find();
                }
                if($v['time']){
                    $v['len'] =  $v['len'] + 40;
                }
            }
        }
        if($ids){
            ChatMessage::where(['id'=>['in',$ids]])->update(['is_read'=>1]);
        }
        $this->success('操作成功',$list);
    }

    //添加访问记录
    public function add_visit(){
	    $visit_user_id=$this->request->request('visit_user_id');
	    if($visit_user_id!=$this->user['id']){
	        $visit=Visit::where(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id))->find();
	        if($visit){
	            Visit::where(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id))->update(array('add_time'=>time()));
	        }else{
	            Visit::insert(array('user_id'=>$this->user['id'],'visit_user_id'=>$visit_user_id,'add_time'=>time()));
	        }
	    }
        $this->success('操作成功');
	}
    //点击关注
	public function follow(){
		$user_id=$this->request->request('item_user_id',0);
		if(!$user_id){
            $this->error('缺少参数');
		}
		$u=UserModel::where(array('id'=>$user_id))->find();
		if(!$u){
            $this->error('关注对象用户不存在');
		}
		$fans_user_id=$this->user['id'];
		$follow=Follow::where(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id))->find();
		if(!$follow){
			Follow::insert(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id,'is_read'=>1,'add_time'=>time()));
			UserModel::where(array('id'=>$this->user['id']))->update(array('read_message'=>1));
            $this->success('关注成功');
		}else{
            $this->success('已关注');
		}
	}
    //获取用户地址
	public function default_user_address(){
		$address_id	=	$this->request->request('address_id','');
        if($address_id){
            $address	=	UserAddress::where(array('user_id'=>$this->user['id'],'id'=>$address_id))->find();
        }else{
            $address	=	UserAddress::where(array('user_id'=>$this->user['id'],'is_default'=>1))->find();		
        }
		if(!$address){
			$address =	UserAddress::where(array('user_id'=>$this->user['id']))->order('add_time desc')->limit(0,1)->find();				
		}   
        $this->success('操作成功',$address);
	}
    //添加用户地址
	public function user_address_save(){
		$id	=	$this->request->request('id','');
		$name	=	$this->request->request('name','');
		$mobile	=	$this->request->request('mobile','');
		$province	=	$this->request->request('province','');
		$city	=	$this->request->request('city','');
		$district	=	$this->request->request('district','');
		$address	=	$this->request->request('address','');
		$postcode	=	$this->request->request('postcode','');
		$is_default	=	$this->request->request('is_default','');
		$is_foreign	=	$this->request->request('is_foreign','中国');
		$select	=	$this->request->request('select','');
        if(empty($name)){
            $this->error('联系人不能为空');
		}
        if(empty($mobile) || (!check_phone($mobile) && $is_foreign == '中国')){
            $this->error('请输入有效的手机号码');
		}
        if( $is_foreign == '中国' && (empty($province) || empty($city) || empty($district) || $province == 'undefined' || $city == 'undefined' || $district == 'undefined')){
            $this->error('所在地区错误');
		}
        if(empty($address)){
            $this->error('详细地址不能为空');
		}
        if($is_foreign == '英国' && !$postcode){
            $this->error('邮编不能为空');
		}
        if($postcode){
            $a = str_replace(" ", "", $postcode);
            if(strlen($a) >= 4 && strlen($a) <= 8){
                if(is_numeric($a[0])) $this->error('请输入正确邮编');
                if(is_numeric($a[strlen($a)-1])) $this->error('请输入正确邮编');

                if(strlen($a) == 4){
                    if(is_english($a[1])) $this->error('请输入正确邮编');
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 5){
                    //第一个和最后一个肯定是
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 6){
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 7){
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                    if(is_english($a[4])) $this->error('请输入正确邮编');
                }elseif(strlen($a) == 8){
                    if(is_numeric($a[1])) $this->error('请输入正确邮编');
                    if(is_english($a[2])) $this->error('请输入正确邮编');
                    if(is_english($a[3])) $this->error('请输入正确邮编');
                    if(is_english($a[4])) $this->error('请输入正确邮编');
                    if(is_english($a[5])) $this->error('请输入正确邮编');
                    if(is_numeric($a[6])) $this->error('请输入正确邮编');
                }
            }else{
                $this->error('请输入正确邮编');
            }
        }
        if($is_foreign != '中国'){
            $arr = explode('-',$select);
            $district = '';
            $city = '';
            if(count($arr) == 1){
                $province = $arr[0];
            }elseif(count($arr) == 2){
                $province = $arr[0];
                $city = $arr[1];
            }
        }

        $arr = [
            'user_id'=>$this->user['id'],
            'name'=>$name,
            'mobile'=>$mobile,
            'province'=>$province,
            'city'=>$city,
            'district'=>$district,
            'address'=>$address,
            'postcode'=>$postcode,
            'is_default'=>$is_default,
            'add_time'=>time(),
            'is_foreign'=>$is_foreign == '中国' ? 0 : 1,
            'country'=>$is_foreign,
            'country_id'=>AreaWorldwide::where(['name'=>$is_foreign])->value('id')
        ];
        if($id){
            $res	=	UserAddress::where(['id'=>$id])->update($arr);
        }else{
            $res = $id	=	UserAddress::insertGetId($arr);
        }
		if($res){
            $this->success('操作成功',$id);
		}else{
            $this->success('操作失败');
        }
        
	}
    //取消关注
	public function follow_cancel(){
		$user_id		=$this->request->request('item_user_id',0);
		$fans_user_id	=$this->user['id'];
		Follow::where(array('user_id'=>$user_id,'fans_user_id'=>$fans_user_id))->delete();
        $this->success('操作成功');
	}
    //聊天举报
    public function user_report(){
        $by_user_id=$this->request->request('by_user_id',0);
        $data = [
            'user_id'=>$this->user['id'],
            'by_user_id'=>$by_user_id,
            'add_time'=>time()
        ];
        UserReport::insert($data);
    }

    //获取总未读消息数量
    public function get_user_message_count(){
        $user_id=$this->request->request('user_id',0);
		$where1 = ['js_user_id'=>$user_id,'status'=>1,'is_read'=>0];
		$is_read_count = ChatMessage::where($where1)->count();
		if($is_read_count > 99){
			$is_read_count  = 99;
		}
        $this->success('操作成功',$is_read_count);
    }
    //群操作
    public function finish_board(){
        $group_chat_id = $this->request->request('group_chat_id');
        $group_name = $this->request->request('group_name','');
        $type = $this->request->request('type',0); // 0是已读操作  1是修改群昵称  2是修改群聊名称  3是修改群公告  4退出群聊
        if(!$group_chat_id){
            $this->error('操作失败');
        }
        if($type == 0){
            $update = ['is_content'=>1];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }elseif($type == 1){
            $update = ['group_name'=>$group_name];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }elseif($type == 2){
            $update = ['name'=>$group_name];
            GroupChat::where(['id'=>$group_chat_id])->update($update);
        }elseif($type == 3){ 
            $update = ['content'=>$group_name];
            GroupChat::where(['id'=>$group_chat_id])->update($update);
            GroupChatUser::where(['group_chat_id'=>$group_chat_id])->update(['is_content'=>0]);
        }elseif($type == 4){ 
            $update = ['status'=>-1];
            GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->update($update);
        }
        $this->success('操作成功');
    }
    
    //获取消息列表
    public function get_user_message(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = [
            'status'=>1,
            'user_id'=>$this->user['id'],
            'is_group_chat'=>0
        ];
        $where1 = [
            'status'=>1,
            'js_user_id'=>$this->user['id'],
            'is_group_chat'=>0
        ];

        $subQuery = ChatMessage::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->field('max(add_time) as add_time')->group('sort')->buildSql();

        if($this->user['id'] == 439){
            $where['a.is_system_chat'] = 0;
            $where1['a.is_system_chat'] = 0;
            $list = ChatMessage::alias('a')
            ->field("a.*")
            ->where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })
            ->group('sort')
            ->order('add_time desc')
            ->join("$subQuery b","b.add_time = a.add_time") // 关键点
            ->limit(($page-1)*$pagesize,$pagesize)
            ->select();
          
        }else{
            $list = ChatMessage::alias('a')
            ->field("a.*")
            ->where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })
            ->group('sort')
            ->order('add_time desc')
            ->join("$subQuery b","b.add_time = a.add_time") // 关键点
            ->limit(($page-1)*$pagesize,$pagesize)
            ->select();
        }

        //获取消息列表
        // $list = ChatMessage::where($where)
        // ->whereOr(function($query) use ($where1){
        //     $query->where($where1);
        // })->group('sort')->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        $arr = [];
        if($list){
            foreach ($list as $k=>&$info) {
                //$info =  ChatMessage::where(['status'=>1,'sort'=>$v['sort']])->order('add_time desc')->find();
                if($info['user_id'] == $this->user['id']){
                    $where = ['id'=>$info['js_user_id']];
                }else{
                    $where = ['id'=>$info['user_id']];
                }
                $info['user'] = UserModel::where($where)->find();
                $info['add_time'] = date('m-d H:i:s',$info['add_time']);
                //查询未读消息数量
                $info['wd'] = ChatMessage::where(['status'=>1,'sort'=>$info['sort'],'is_read'=>0,'js_user_id'=>$this->user['id']])->count();
                $info['img'] = '';
                $info['shop_user_id'] = 0;
                //查询图片
                if($info['product_id']){
                    $res = Product::where(['id'=>$info['product_id']])->find();
                    $info['img'] = $res['video_img'];
                    $info['shop_user_id'] = $res['user_id'];
                }elseif($info['wish_id']){
                    $res = ProductWish::where(['id'=>$info['wish_id']])->find();
                    $info['img'] = $res['video_img'];
                    $info['shop_user_id'] = $res['user_id'];
                }
                //$arr[] = $info;
            }

            //$sort = array_column($arr,'add_time');
            //array_multisort($sort,SORT_DESC,$arr);
        }
        $message['list'] = $list;
        $message['sys']=ProductMessage::field('title,add_time')->where(array('type'=>3,'to_user_id'=>$this->user['id']))->order('add_time desc')->limit(0,1)->find();
		if($message['sys']){
			$message['sys']['add_time']=date("Y-m-d H:i:s",$message['sys']['add_time']);
		}else{
		    $message['sys']="";
		}
		$message['sys_unread']=ProductMessage::where(array('type'=>3,'to_user_id'=>$this->user['id'],'is_read'=>0))->count();
        //查询群聊
        $where = [
            'status'=>1  
        ];
        $res = GroupChat::where($where)->select();
        $arr = [];
        if($res){
            foreach ($res as $v) {
                $d = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$v['id'],'status'=>1])->find();
                if($d){
                    $v['is_content'] = $d['is_content'];
                    $arr[] = $v;
                }
            }
        }
        $message['groupChatList'] = $arr;
        $this->success('获取成功',$message);
    }

    //撤回聊天记录
    public function delete_chat_message(){
        $id = $this->request->request('id');
        $res = ChatMessage::where(['id'=>$id])->update(['status'=>-1]);
        if($res){
            $this->success('撤回成功');
        }else{
            $this->error('撤回失败');
        }
    }
    
    //获取群用户人数
    public function groupChatUserList(){
        $group_chat_id = $this->request->request('group_chat_id',0);
        $where = [
            'a.group_chat_id'=>$group_chat_id,
            'a.status'=>1
        ];
        $list = GroupChatUser::alias('a')
        ->field("b.avatar,b.nickname,a.user_id")
        ->where($where)
        ->order('grade asc')
        ->join("user b","b.id = a.user_id") // 关键点
        ->limit(0,20)
        ->select();
        $group_name = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->value('group_name');
        if(!$group_name){
            $group_name = $this->user['nickname'];
        }
        $this->success('获取成功',['list'=>$list,'group_name'=>$group_name]);
    }

    //获取聊天内容
    public function getmessageList(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        $group_chat_id = $this->request->request('group_chat_id',0);
        $page=$this->request->request('page',1);
		$pagesize= $this->request->request('pagesize',20);
        
        if(!$sort){
            $where = [
                'status'=>1,
                'user_id'=>$this->user['id'],
                'product_id'=>$product_id,
                'wish_id'=>$wish_id,
                'js_user_id'=>$js_user_id,
                'is_group_chat'=>$is_group_chat
            ];
            $where1 = [
                'status'=>1,
                'user_id'=>$js_user_id,
                'product_id'=>$product_id,
                'wish_id'=>$wish_id,
                'js_user_id'=>$this->user['id'],
                'is_group_chat'=>$is_group_chat
            ];
            $list = ChatMessage::where($where)
            ->whereOr(function($query) use ($where1){
                $query->where($where1);
            })->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        }else{
            //查询该用户入群时间
            $where = [
                'status'=>1,
                'sort'=>$sort,
                'is_group_chat'=>$is_group_chat
            ];
            if($is_group_chat){
                $add_time = GroupChatUser::where(['user_id'=>$this->user['id'],'group_chat_id'=>$group_chat_id])->value('add_time');
                $where['add_time'] = ['>',$add_time];
            }
            $list = ChatMessage::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        }

        $ids = [];
        $arrPX1 = [];
        if($list){
            //执行排序
            if($page == 1){
                foreach ($list as $k=>&$v) {
                    $arrPX1[$k] =  $v['id'];
                }
                array_multisort($arrPX1, SORT_ASC, $list);
            }
            $avatar = UserModel::where(['id'=>$this->user['id']])->value('avatar');
            $last_time = 0;
            foreach ($list as $k=>&$v) {
                if($v['is_group_chat'] == 1){ //群聊消息
                    $where = ['id'=>$v['user_id']];
                }else{
                    //查看用户信息
                    if($v['user_id'] == $this->user['id']){
                        //他发给我的
                        $where = ['id'=>$v['js_user_id']];
                        if($v['user_id'] == $v['js_user_id']){
                            $ids[] = $v['id'];
                        }
                    }else{
                        //我发给他的
                        if($v['is_read'] == 0){
                            //如果有未读消息则更新为已读
                            $ids[] = $v['id'];
                        }
                        $where = ['id'=>$v['user_id']];
                    }
                }
                $v['avatar'] = $avatar;
                $v['user'] = UserModel::field('id,nickname,avatar')->where($where)->find();
                $group_name = GroupChatUser::where(['user_id'=>$v['user_id'],'group_chat_id'=>$group_chat_id])->value('group_name');
                if($group_name){
                    $v['user']['nickname'] = $group_name;
                }
                $v['time'] = '';
                if(!$last_time){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }elseif(($v['add_time'] - $last_time) > 7600){
                    $v['time'] =  date('m-d H:i',$v['add_time']);
                    $last_time = $v['add_time'];
                }
                $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                $v['len'] = 0;
                if($v['type'] == 1){ //文字
                    //判断发布文字有多少个字
                    $len = mb_strlen($v['content'], 'UTF-8');
                    $v['len'] = 135;
                    if($len > 16 && $len <= 32){
                        $v['len'] = 170;
                    }elseif($len > 32 && $len <= 48){
                        $v['len'] = 210;
                    }elseif($len > 48 && $len <= 64){
                        $v['len'] = 250;
                    }elseif($len > 64 && $len <= 80){
                        $v['len'] = 290;
                    }elseif($len > 80 && $len <= 96){
                        $v['len'] = 330;
                    }elseif($len > 96 && $len <= 122){
                        $v['len'] = 370;
                    }elseif($len > 122 && $len <= 138){
                        $v['len'] = 410;
                    }elseif($len > 138){
                        $v['len'] = 450;
                    }
                }elseif($v['type'] == 2){ //图片
                    $v['len'] = 290;
                }elseif($v['type'] == 3){ //商品
                    $v['len'] = 270;
                    $v['product'] = Product::field('id,video_img,title,price')->where(['id'=>$v['goods_id']])->find();
                }
                if($v['time']){
                    $v['len'] = $v['len'] + 40;
                }
            }
        }
        if($ids){
            ChatMessage::where(['id'=>['in',$ids]])->update(['is_read'=>1]);
        }
        
        $this->success('操作成功',$list);
    }
    //新增聊天内容
    public function add_report(){
        $product_id = $this->request->request('id',0);
        $wish_id = $this->request->request('wish_id',0);
        $sort = $this->request->request('sort','');
        $js_user_id = $this->request->request('js_user_id',0);
        $titleReport = $this->request->request('titleReport','');
        $img = $this->request->request('img','');
        $type = $this->request->request('type',1);
        $goods_id = $this->request->request('goods_id',0);
        $is_group_chat = $this->request->request('is_group_chat',0);
        // if(!$titleReport && !$img){
        //     $this->error('聊天内容不能为空');
        // }

        $data = [
            'add_time'=>time(),
            'product_id'=>$product_id,
            'content'=>trim($titleReport),
            'wish_id'=>$wish_id,
            'img'=>$img,
            'type'=>$type ? $type : 1,
            'goods_id'=>$goods_id,
            'is_group_chat'=>$is_group_chat
        ];
        //群聊消息
        if($is_group_chat){
            $data['user_id'] = $this->user['id'];
        }else{ //私聊消息
            if(!$sort){
                //查询上一条消息
                $where = [
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'status'=>1,
                    'user_id'=>$this->user['id'],
                    'js_user_id'=>$js_user_id,
                ];
                $where1 = [
                    'product_id'=>$product_id,
                    'wish_id'=>$wish_id,
                    'status'=>1,
                    'user_id'=>$js_user_id,
                    'js_user_id'=>$this->user['id'],
                ];
                //获取消息列表
                $info = ChatMessage::where($where)->whereOr(function($query) use ($where1){
                    $query->where($where1);
                })->order('add_time desc')->find();
                if(!$info){
                    $sort = $js_user_id.$wish_id.$product_id.$this->user['id'];
                    if($js_user_id == $this->user['id']){
                        $this->error('不能给自己发消息');
                    }
                }else{
                    $sort = $info['sort'];
                }
                
            }
            $info = ChatMessage::where(['sort'=>$sort])->find();
            
            if($info){
                if($this->user['id'] == $info['user_id'] ){
                    $data['user_id'] = $info['user_id'];
                    $data['js_user_id'] = $info['js_user_id'];
                }else{
                    $data['user_id'] = $info['js_user_id'];
                    $data['js_user_id'] = $info['user_id'];
                }
            }else{
                $data['user_id'] = $this->user['id'];
                $data['js_user_id'] = $js_user_id;
            }
        }
        $data['sort'] = $sort;
        
        $id = ChatMessage::insertGetId($data);
        //发送成功给接受者发送推送消息
        $geTui = new GeTui();
        //添加成功执行推送逻辑
        $cid = UserModel::where(['id'=>['in',$data['js_user_id']]])->value('cid');
        if($cid){
            $geTui->pushToSingleByCid($cid,'消息提醒','你有一条新的消息,请注意查收','/pages/message/message');
        }
        $this->success('发送成功',$id);
    }

    //我的邀请
	public function my_invite(){
		$type= $this->request->request('type',1);
        if($type == 1){ //查询我的邀请详情
            $page= $this->request->request('page',1);
            $pagesize= $this->request->request('pagesize',10);
            $where = [
                'invite_user_id'=>$this->user['id']
            ];
            $month_log = UserModel::field('id,nickname,avatar,add_time')->where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
            foreach($month_log as $a=>&$v){
                $v['add_time']=date("Y-m-d",$v['add_time']);
                //查询该用户是否发过商品
                $res = Product::where(['user_id'=>$v['id'],'status'=>1,'is_del'=>0])->find();
                $v['is_yx'] = $res ? 1 : 0;
            }
        }else{
            $where = [
                'invite_user_id'=>$this->user['id']
            ];
            $month_log = UserModel::field('id,nickname,avatar,add_time')->where($where)->order('add_time desc')->select();
            $num = 0; //有效用户
            foreach($month_log as &$v){
                //查询该用户是否发过商品
                $res = Product::where(['user_id'=>$v['id'],'status'=>1,'is_del'=>0])->find();
                if($res){
                    $num += 1;
                }
            }
            $month_log = [
                'sum'=>count($month_log),
                'num'=>$num,
                'score'=>count($month_log) * 10
            ];
        }
		
        $this->success('发送成功',$month_log);
	}
    
    //获取用户信息
    public function getUser(){
        $user = UserModel::where('id',$this->user['id'])->find();
        if($user){
            $where = [];
            $where['status']=1;
            $where['is_sale']=0;
            $where['price']=['elt',$user['rose_money']];
            $goods_num =Product::where($where)->count();
            //判断该用户是否是商家
            $info = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();
            $user['is_shop'] = $info?1:0;
            $this->success('获取成功',['user'=>$user,'goods_num'=>$goods_num]);
        }
    }

    //更新用户cid
    public function updateCid(){
        $cid = $this->request->request('cid','');
        if($cid){
            UserModel::where('id',$this->user['id'])->update(['cid'=>$cid]);
        }
        $this->success('操作成功');
    }

    //删除评论
    public function del_comment(){
		$id=$this->request->request('id',0);
		if($id){
            $where = [
                'id'=>$id,
                'user_id'=>$this->user['id'],
                'type'=>0
            ];
			$ProductMessage=ProductMessage::where($where)->find();
			if(!$ProductMessage){
				$this->error('操作失败');
			}
            ProductMessage::where($where)->delete();
            $this->success('删除成功');
		}else{
			$this->error('缺少参数');
		}	
	}

    //个人主页-接口
	public function homepage(){
		$user_id=$this->request->request('user_id');
		$user=UserModel::where(array('id'=>$user_id))->find();
		$user['follow_count']=Follow::where(array('fans_user_id'=>$user_id))->count();
		$user['fans_count']=Follow::where(array('user_id'=>$user_id))->count();
		$product_ids=Product::where(array('user_id'=>$user_id))->column('id');
		if(count($product_ids)>0){
			$user['product_count']=count($product_ids);
		}else{
			$user['product_count']=0;
			$product_ids=[0];
		}
		$user['love_count']=Love::where(array('product_id'=>array('in',$product_ids)))->count();
		$user['visit_count']=Visit::where(array('visit_user_id'=>$user_id))->count();//访客数量
		//待确认数量
		$user['confirm_count']=UserOrder::where(array('product_id'=>array('in',$product_ids),'status'=>1))->count();
		//卖出数量提示
		$user['delivery_count']=UserOrder::where(array('product_id'=>array('in',$product_ids),'status'=>2))->count();
		$user['maichu_count']=$user['delivery_count'];
		//买入订单提示
		$user['recieve_count']=UserOrder::where(array('user_id'=>$user_id,'status'=>2))->count();
		$user['mairu_count']=$user['recieve_count'];
		//待评价
		$user['nomessage_count']=UserOrder::where(array('user_id'=>$user_id,'status'=>4))->count();
		
        $user['rose_in']=UserRoseLog::where(['user_id'=>$user_id,'rose_money'=>array('gt',0),'type'=>['neq',18]])->sum('rose_money');
        $user['rose_level']=rose_level($user['rose_in']);
        $user['level_name']=level_name($user['rose_in']);
        //余享号
		$user['yxh']=$user['id']+10000;
		
		$follow=Follow::where(array('fans_user_id'=>$this->user['id'],'user_id'=>$user_id))->find();
		$user['is_follow']=$follow?1:0;
		
		$user['kefu']=ConfigData::where(array('name'=>'kefu_token'))->value('value');
		$user['xcx_qun_ewm']=ConfigData::where(array('name'=>'xcx_qun_ewm'))->value('value');
		$user['sdk_version']='1.3.4';

        //判断该用户是否是商家
        $info = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();
        if($info){
            $user['shop_id'] = $info['id'];
            $user['is_shop'] = 1;
        }
        $user['shop'] = Shop::where(['user_id'=>$user['id'],'status'=>1])->find();
        $this->success('获取用户信息',['user'=>$user]);
	}
    //获取状态
    public function getStatusTask(){
        $autocity = $this->request->request('autocity','');
        $data = [
            'task0'=>0,
            'task1'=>0,
            'task2'=>0,
            'task3'=>0,
            'task4'=>0,
            'task5'=>0,
            'task6'=>0,
            'task7'=>0,
            'task9'=>0,
            'task10'=>0,
        ];
        
        $rose_money = 0;
        if($this->user){ //登录了
            $rose_money = $this->user['rose_money'];

            // if($autocity == '孝感市'){  //宝忠
            //     $time =  strtotime(date('Y-m-d',time()));
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>1,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task1'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>2,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task2'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>3,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     if($info){
            //         $data['task3'] = $info['status'] == 0 ? 1 : 2;
            //     }
            //     // $info = TaskImg::where(['user_id'=>$this->user['id'],'type'=>4,'add_time'=>['>',$time],'status'=>['neq',-1]])->find();
            //     // if($info){
            //     //     $data['task4'] = $info['status'] == 0 ? 1 : 2;
            //     // }
            // }else{
            $data = [];
            $redis = redis_init();
            //看广告
            $name = 'add_score_26_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task0'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task0'] = 1; 
                }
            }

            //每日分享小程序到微信/社群
            $name = 'add_score_21_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task1'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task1'] = 1; 
                }
            }
            //每日成功发布一个闲置
            $info = $redis->get($this->user['id'].'roseandlog');	
            if(!$info){
                $data['task2'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task2'] = 1; 
                }
            }

            //每日成功发布一个心愿
            $info = $redis->get($this->user['id'].'ProductWish');	
            if(!$info){
                $data['task3'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task3'] = 1; 
                }
            }
            
            //每日分享我的闲置到微信/社群
            // $name = 'add_score_24_'.$this->user['id'];
            // $info = $redis->get($name);
            // if(!$info){
            //     $data['task4'] = 1; 
            // }else{
            //     //判断发布时间
            //     $time1 = date('Y-m-d',$info);
            //     $time2 = date('Y-m-d',time());
            //     if($time1 != $time2){
            //         $data['task4'] = 1; 
            //     }
            // }

            //每日发布一条动态
            $name = $this->user['id'].'CommunityModel';
            $info = $redis->get($name);
            if(!$info){
                $data['task4'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task4'] = 1; 
                }
            }

            //关注公众号奖励
            $name = 'add_score_22_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task5'] = 1; 
            }

            //添加官方小助手
            $name = 'add_score_23_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task6'] = 1; 
            }
            //首次订单完成
            $name = 'add_score_25_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task7'] = 1; 
            }
            
            //每日签到
            $name = 'add_score_27_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task9'] = 1; 
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $data['task9'] = 1; 
                }
            }
            //更新头像和昵称   
            $name = 'add_score_28_'.$this->user['id'];
            $info = $redis->get($name);
            if(!$info){
                $data['task10'] = 1; 
            }
        }
        $this->success('获取成功',['data'=>$data,'rose_money'=>$rose_money]);
    }

    //管理员冻结用户
    public function admin_freeze_user(){
        $user_id = $this->request->request('user_id','');
        if($this->user['is_admin'] != 1){
            $this->error('没有权限操作!');
        }
        Db::startTrans();
		try {
            if($user_id){
                $res = UserModel::where('id',$user_id)->update(['status'=>0]);
                if($res){
                    //该用户所有上架的信息全部下架
                    Product::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    ProductWish::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    Community::where(['user_id'=>$user_id])->update(['status'=>-1]);
                    Db::commit();
                    $this->success('冻结成功');
                }else{
                    Db::commit();
                    $this->error('冻结失败');
                }
            }else{  
                Db::commit();
                $this->error('冻结失败');
            }
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
    }

    //管理员下架动态/心愿/闲置
    public function admin_xj(){
        $id = $this->request->request('id','');
        $type = $this->request->request('type','1');
        if($this->user['is_admin'] != 1){
            $this->error('没有权限操作!');
        }
        if($id){
            if($type == 1){ //闲置
                $res = Product::where('id',$id)->update(['status'=>-1]);
            }elseif($type == 2){  //心愿
                $res = ProductWish::where('id',$id)->update(['status'=>-1]);
            }else{  //动态
                $res = Community::where('id',$id)->update(['status'=>-1]);
            }
            if($res){
                $this->success('下架成功');
            }else{
                $this->error('下架失败');
            }
        }else{
            $this->error('下架失败');
        }
    }

    //更新个人资料
	public function profile_save(){
        $data = [];
        $this->request->request('nickname','') ? $data['nickname'] = $this->request->request('nickname','') : '' ; 
        $this->request->request('avatar','') ? $data['avatar'] =  $this->request->request('avatar','') : '' ;
        $this->request->request('profile','') ? $data['profile'] =  $this->request->request('profile','') : '' ;
        $this->request->request('gender','') ? $data['gender'] =  $this->request->request('gender','') : '' ;
        $this->request->request('birthday','') ? $data['birthday'] =  $this->request->request('birthday','') : '' ;
        $this->request->request('city','') ? $data['city'] =  $this->request->request('city','') : '' ;
        $this->request->request('bgimg','') ? $data['bgimg'] =  $this->request->request('bgimg','') : '' ;
        $this->request->request('tags','') ? $data['tags'] =  $this->request->request('tags','') : '' ;
        $this->request->request('identityid','') ? $data['identityid'] =  $this->request->request('identityid','') : '' ;
        $this->request->request('weixin','') ? $data['weixin'] =  $this->request->request('weixin','') : '' ;
        $mobile = $this->request->request('mobile','');
		if(!empty($mobile) && $mobile!=$this->user['mobile']){
		    $code=$this->request->request('code','');
		    if(empty($code)){
                $this->error('请输入验证码');
		    }
		    $mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
			if($code!=$mobile_code['code']){
                $this->error('验证码错误');
			}
			if(check_phone($mobile)){
			    $data['mobile']=$mobile;
			}else{
                $this->error('新手机号码无效');
			}
		}
		if(!empty($data)){
			UserModel::where(array('id'=>$this->user['id']))->update($data);
            $name = 'add_score_28_'.$this->user['id']; 
            $name1 = 'add_score_28_avatar_'.$this->user['id']; //头像
            $name2 = 'add_score_28_nickname_'.$this->user['id']; //昵称
            $name3 = 'add_score_28_gender_'.$this->user['id']; //性别
            $name4 = 'add_score_28_birthday_'.$this->user['id'];  //生日
            $name5 = 'add_score_28_city_'.$this->user['id']; //地区
            $redis = redis_init();
            if(!$redis->get($name)){
                if(!empty($data['avatar'])){
                    if($redis->get($name2) && $redis->get($name3) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name1,1);
                    }
                }
                if(!empty($data['nickname'])){
                    if($redis->get($name1) && $redis->get($name3) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name2,1);
                    }
                }
                if(!empty($data['gender'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name4) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name3,1);
                    }
                }
                if(!empty($data['birthday'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name3) && $redis->get($name5) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name4,1);
                    }
                }
                if(!empty($data['city'])){
                    if($redis->get($name1) && $redis->get($name2) && $redis->get($name3) && $redis->get($name4) ){ 
                        roseandlog($this->user['id'],2,28,'完善个人资料奖励');
                        $redis->set($name,1);
                    }else{  //未上传则记录昵称已更新
                        $redis->set($name5,1);
                    }
                }
            }
            $this->success('修改成功');
		}else{
            $this->error('请输入修改内容');
		}
	}

    //给用户添加积分
    public function add_score(){
        $type = $this->request->post('type');
        $score = $this->request->post('score');
        if($type == 21){  //分享好友奖励
            $name = 'add_score_21_'.$this->user['id'];
            $title = '每日分享小程序到微信/社群';
        }elseif($type == 22){  //关注公众号奖励
            $name = 'add_score_22_'.$this->user['id'];
            $title = '关注公众号奖励';
        }elseif($type == 23){  //加小助手微信号奖励
            $name = 'add_score_23_'.$this->user['id'];
            $title = '加小助手微信号奖励';
        }elseif($type == 24){  //分享闲置商品奖励
            $name = 'add_score_24_'.$this->user['id'];
            $title = '每日分享闲置商品';
        }elseif($type == 26){  //分享闲置商品奖励
            $name = 'add_score_26_'.$this->user['id'];
            $title = '广告奖励';
        }elseif($type == 27){  //分享闲置商品奖励
            $name = 'add_score_27_'.$this->user['id'];
            $title = '签到奖励';
        }elseif($type == 30){  //分享抽奖得积分
            $name = 'add_score_30_'.$this->user['id'];
            $title = '分享抽奖得积分';
        }
        $redis = redis_init();
        $info = $redis->get($name);
        if(!$info){
            //未获取过奖励则直接给奖励
            roseandlog($this->user['id'],$score,$type,$title);
            $redis->set($name,time());
            $this->success('给奖励成功');
        }else{
            if($type == 21 || $type == 24 || $type == 26 || $type == 27  || $type == 30){
                //判断发布时间
				$time1 = date('Y-m-d',$info);
				$time2 = date('Y-m-d',time());
				if($time1 != $time2){
					//上次发布不是今天 给奖励
					roseandlog($this->user['id'],$score,$type,$title);
					$redis->set($name,time());
                    $this->success('给奖励成功');
				}
            }
        }

        $this->error('今日奖励已获取');
    }
    //账号注销
	public function account_cancel(){
		$mobile=$this->request->request('mobile','');
		$code=$this->request->request('code','');
		if(empty($mobile)){
            $this->error('请输入手机号');
		}
		if(empty($code)){
            $this->error('请输入验证码');
		}
		$mobile_code=MobileCode::where(array('mobile'=>$mobile,'verify'=>0))->order('add_time desc')->limit(0,1)->find();
		if($code!=$mobile_code['code']){
            $this->error('验证码错误');
		}
        //查询该用户是否存在闲置商品
        $info = Product::where(['user_id'=>$this->user['id'],'is_sale'=>0,'status'=>1])->find();
        if($info){
            $this->error('您还有想要送出的闲置,如需注销请先下架闲置商品后进行注销');
        }
		UserModel::where(array('id'=>$this->user['id']))->update(array('mobile'=>$this->user['mobile'].'_2','status'=>-1));
        $this->success('注销成功');
	}


    //我的浏览记录 / 我的收藏
	public function user_product_view(){
		$page=$this->request->request('page',1);
		$pagesize=$this->request->request('pagesize',18);
		$type=$this->request->request('type',1); // 默认是1 我的浏览记录   2我的收藏
        if($type == 1){
            $list=ProductViewLog::where(array('user_id'=>$this->user['id'],'product_id'=>array('gt',0)))->order('add_time desc')->limit($page*$pagesize-$pagesize,$pagesize)->select();
        }else{
            $list=UserCollect::where(array('user_id'=>$this->user['id'],'product_id'=>array('gt',0)))->order('add_time desc')->limit($page*$pagesize-$pagesize,$pagesize)->select();
        }
		if($list){
	    	foreach($list as $a=>&$b){
        		$b['product']=Product::where(array('id'=>$b['product_id'],'status'=>1))->find();
        		if(!$b['product']){
                    unset($list[$a]);
                    continue;
                }
        		if($b['add_time']>strtotime(date("Y-m-d 00:00:01"))){
        		    $b['add_time']="今天";
        		}elseif($b['add_time']>strtotime(date("Y-m-d 00:00:00"))-3600*24){
        		    $b['add_time']="昨天";
        		}elseif($b['add_time']>time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600){
        		    $b['add_time']="本周";
        		}elseif($b['add_time']>strtotime(date("Y-m-01 00:00:00"))){
        		    $b['add_time']="本月";
        		}else{
        		    $b['add_time']=date("Y-m",$b['add_time']);
        		}
		    }
		}
        $list = array_values($list);
		$this->success('获取成功',$list);
	}

    //我的钱包
	public function my_rose(){
		$page=$this->request->post('page',1);
		$pagesize=$this->request->post('pagesize',10);
		$month=$this->request->post('month',date("Y-m"));
		$start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));
		$rose['yue']=$this->user['rose_money'];
		$rose['month_in']=UserRoseLog::where(array('user_id'=>$this->user['id'],'rose_money'=>array('gt',0),'add_time'=>$thismonth))->sum('rose_money');	
		$rose['month_out']=0-UserRoseLog::where(array('user_id'=>$this->user['id'],'rose_money'=>array('lt',0),'add_time'=>$thismonth))->sum('rose_money');	
		$rose['month_log']=UserRoseLog::where(array('user_id'=>$this->user['id'],'add_time'=>$add_time))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as $a=>&$b){
			$b['add_time']=date("Y-m-d H:i:s",$b['add_time']);
		}
        $this->success('获取成功',$rose);
	}

    /**
     * 用户助力
     */
    public function help(){
        $invite_user_id_invite = $this->request->request('invite_user_id_invite','');
        if(!$invite_user_id_invite){
            $this->error('助力参数错误');
        }
        //判断该用户是否已经为该用户助力过
        $redis =redis_init();
        $res = $redis->get($this->user['id'].'help'.$invite_user_id_invite);
        if($res && $res == date('Y-m-d',time())){ //今日已经助力过
            $this->error('不可重复助力');
        }else{
            //今日未助力
            Db::startTrans();
            try {
                $arr = [
                    'user_id'=>$invite_user_id_invite,
                    'title'=>'邀请助力',
                    'type'=>3,
                    'rose_money'=>2,
                    'add_time'=>time()
                ];
                UserRoseLog::insert($arr);
                $user = UserModel::where(['id'=>$invite_user_id_invite])->find();
                UserModel::where(['id'=>$invite_user_id_invite])->update(['rose_money'=>$user['rose_money']+2]);
                $redis->set($this->user['id'].'help'.$invite_user_id_invite,date('Y-m-d',time()));
                Db::commit();
                $this->success('助力成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }
    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    

   

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

       //获取立即邀请页海报
    public function invite_ewm(){
        //查询该用户总共分享过多少件闲置物品
        $bg="uploads/img/25.png";

		$appid='wx7e02d2ebf871c207';
	    $secret='1048ec4292504f8f4b1423b205ddb9b8';
		$res= file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
		$tokens=json_decode($res,true);
		$access_token=$tokens['access_token'];
		
		$url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
		$data=array('page'=>'pages/shop/shopClass','scene'=>$this->user['id'],'width'=>120);
		$res = httpRequest($url, $data, "json");
		//二维码图片地址	
		$qr_code ='uploads/invite/'.time().rand(1000, 9999).'.png';
		file_put_contents($qr_code ,$res);
        $qr_code1 ='uploads/invite/'.time().rand(1000, 9999).'.png';
        $this->resizeImage($qr_code,$qr_code1, 490, 490,490, 490);
        $image = \think\Image::open($bg);
        $img = 'uploads/invite/'.time().rand(1000, 9999).'.png';
        $image->water($qr_code1,[145,660])->save($img); 
        unlink($qr_code);
        unlink($qr_code1);
		$this->success('操作成功','https://'.$_SERVER['HTTP_HOST'].'/'.$img);
    }
   
    /**
    * 处理图片尺寸【等比例缩小或放大】
    * @param $filePath【进行处理图片本地地址】
    * @param $saveImage【处理后保存地址】
    * @param $maxWidth【最大宽度】
    * @param $maxHeight【最大高度】
    * @param $minWith【最小宽度】
    * @param $minHeight【最小高度】
    */
    function resizeImage($filePath, $saveImage, $maxWidth, $maxHeight, $minWith, $minHeight)
    {
        //获取图片基础信息
        $tmpImageSize = getimagesize($filePath);
        $originalImageWidth = $tmpImageSize[0]; //宽度
        $originalImageHeight = $tmpImageSize[1]; //长度
        $originalImageType = $tmpImageSize[2]; //类型
        //保存图片的宽度跟高度
        $targetWidth = $tmpImageSize[0];
        $targetHeight = $tmpImageSize[1];
        //计算图片将要保存的尺寸
        if ($originalImageWidth > $maxWidth) { //图片宽度超过最大限度
            $targetWidth = $maxWidth;
            $targetHeight = $originalImageHeight * ($maxWidth / $originalImageWidth);
        }
        if ($originalImageWidth < $minWith) { //图片宽带小于最小限度
            $targetWidth = $minWith;
            $targetHeight = $originalImageHeight * ($minWith / $originalImageWidth);
        }
        if ($targetHeight > $maxHeight) { //图片高度超过最大限度
            $targetWidth = $targetWidth * ($maxHeight / $targetHeight);
            $targetHeight = $maxHeight;
        }
        if ($targetHeight < $minHeight) { //图片高度小于最小限度
            $targetWidth = $targetWidth * ($minHeight / $targetHeight);
            $targetHeight = $minHeight;
        }
        //最后检验宽度跟高度是否符合【兜底】
        if ($targetWidth < $minWith) {
            $targetWidth = $minWith;
        }
        if ($targetWidth > $maxWidth) {
            $targetWidth = $maxWidth;
        }
        if ($targetHeight < $minHeight) {
            $targetHeight = $minHeight;
        }
        if ($targetHeight > $maxHeight) {
            $targetHeight = $maxHeight;
        }
        //四舍五入
        $targetWidth = ceil($targetWidth);
        $targetHeight = ceil($targetHeight);
        //判断图片格式进行处理
        if ($originalImageType == 1) {
            $temPic = imagecreatefromgif($filePath);
        } else if ($originalImageType == 2) {
            $temPic = imagecreatefromjpeg($filePath);
        } else if ($originalImageType == 3) {
            $temPic = imagecreatefrompng($filePath);
        } else {
            exit();
        }
        //保存图片
        $thPic = imagecreatetruecolor($targetWidth, $targetHeight);
        // 调整默认颜色
        $color = imagecolorallocate($thPic, 255, 255, 255);
        imagefill($thPic, 0, 0, $color);
        //裁剪
        imagecopyresampled($thPic, $temPic, 0, 0, 0, 0, $targetWidth, $targetHeight,
        $originalImageWidth, $originalImageHeight);
        //保存图片
        imagejpeg($thPic, $saveImage);
    }
}
